import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { InjectionKey } from 'vue'
import { IMenu, IUserInfo } from '@/api/types/common'
import { getItem, setItem } from '@/utils/storage'
import { USER, MENU } from '@/utils/constans'
const state = {
  isCollapse: false,
  user: getItem<{ token: string } & IUserInfo>(USER),
  menus: getItem<IMenu>(MENU) || [] as IMenu[]
}
export type State = typeof state

export const key:InjectionKey<Store<State>> = Symbol('store')

export const store = createStore<State>({
  state,
  mutations: {
    setIsCollapse (state, payload) {
      state.isCollapse = payload
    },
    setUser (state, payload) {
      state.user = payload
      setItem(USER, state.user)
      // window.localStorage.setItem('user', JSON.stringify(state.user))
    },
    setMenus (state, payload) {
      state.menus = payload
      setItem(MENU, state.menus)
    }
  }
})

// 封装简化后的useStore方法
export function useStore () {
  return baseUseStore(key)
}
